import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

public class Quest implements Runnable{
    private Proxy proxy;
    private String link;
    private String path;

    public Quest(Proxy proxy,String link, String path) {
        this.proxy = proxy;
        this.link = link;
        this.path = path;
    }

    @Override
    public void run() {
        try {
            HT.Log("Try ==>> "+link);
            doGetImage(path,link);
        } catch (Exception e) {
        }
    }

    private void doGetImage(String path, String link) throws Exception {
        URL url = new URL(link);
        URLConnection connection = proxy == null ? url.openConnection() : url.openConnection(proxy);
        connection.setRequestProperty("accept", "*/*");
//        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36");
        Map<String, List<String>> map = connection.getHeaderFields();
        String resp = map.get(null).get(0);
        if (resp.equals("HTTP/1.1 200 OK")) {
            System.out.println("开始以单图模式下载。");
            System.out.println("==> " + link);
            String ContentDisposition = connection.getHeaderField("Content-Disposition"); // 获取响应体
            String byteName = new String(ContentDisposition.getBytes("ISO-8859-1"), "GBK"); // 获取文件名
            String fileName = URLDecoder.decode(byteName.substring(byteName.indexOf("filename=") + 9), "UTF-8").replace("\"", ""); // 转码并提取
            File file = new File(path + fileName);
            Long fileSize = file.length();
            Integer maxSize = connection.getContentLength();
            while (!file.exists() || fileSize < maxSize) {
                int byteSum = 0;
                int byteCur = 0;
                InputStream in = connection.getInputStream();
                FileOutputStream fs = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                while ((byteCur = in.read(buffer)) != -1) {
                    byteSum += byteCur;
                    fs.write(buffer, 0, byteCur);
                }
                in.close();
                fs.flush();
                fs.close();
                fileSize = file.length();
            }
        } else {
            System.out.println("单图模式下载失败，切换到多图模式。");
            doGetImages(path, link);
        }
    }

    private void doGetImages(String path, String link) throws Exception {
        Integer index = 0;
        while (true) {
            index++;
            URL url = new URL(link);
            URLConnection connection = proxy == null ? url.openConnection() : url.openConnection(proxy);
            connection.setRequestProperty("accept", "*/*");
//        connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36");
            Map<String, List<String>> map = connection.getHeaderFields();
            String resp = map.get(null).get(0);
            if (resp.equals("HTTP/1.1 200 OK")) {
                System.out.println("开始以多图模式下载。");
                System.out.println("==> " + link);
                String ContentDisposition = connection.getHeaderField("Content-Disposition"); // 获取响应体
                String byteName = new String(ContentDisposition.getBytes("ISO-8859-1"), "GBK"); // 获取文件名
                String fileName = URLDecoder.decode(byteName.substring(byteName.indexOf("filename=") + 9), "UTF-8").replace("\"", ""); // 转码并提取
                File file = new File(path + fileName);
                Long fileSize = file.length();
                Integer maxSize = connection.getContentLength();
                while (!file.exists() || fileSize < maxSize) {
                    int byteSum = 0;
                    int byteCur = 0;
                    InputStream in = connection.getInputStream();
                    FileOutputStream fs = new FileOutputStream(file);
                    byte[] buffer = new byte[1024];
                    while ((byteCur = in.read(buffer)) != -1) {
                        byteSum += byteCur;
                        fs.write(buffer, 0, byteCur);
                    }
                    in.close();
                    fs.flush();
                    fs.close();
                    fileSize = file.length();
                }
            } else {
                if (index == 1)
                    System.out.println("多图模式下载失败，请检查作品是否存在；若使用了代理模式，请确保代理可用。");
                break;
            }
        }
    }
}
